"""命令行接口模块"""
import sys
import argparse
from pathlib import Path
from . import __version__
from .compiler import Compiler
from .config import Config
from .logger import get_logger

def main():
    """命令行入口函数"""
    parser = argparse.ArgumentParser(
        description=f"py2so v{__version__} - 将Python文件编译为.so二进制模块",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter
    )
    
    # 基本参数
    parser.add_argument(
        "files", nargs='+', help="要编译的一个或多个.py文件路径"
    )
    parser.add_argument(
        "--keep", action="store_true", help="保留原始Python源文件"
    )
    parser.add_argument(
        "-o", "--output", help="指定输出目录"
    )
    parser.add_argument(
        "-v", "--verbose", action="store_true", help="显示详细日志信息"
    )
    parser.add_argument(
        "-V", "--version", action="version", version=f"%(prog)s {__version__}"
    )
    
    # 编译选项
    compile_group = parser.add_argument_group("编译选项")
    compile_group.add_argument(
        "--optimize", type=int, default=0, choices=[0, 1, 2, 3],
        help="优化级别，0-3"
    )
    compile_group.add_argument(
        "--lang-level", type=int, default=3, choices=[2, 3],
        help="Python语言版本级别"
    )
    
    args = parser.parse_args()
    
    # 配置初始化
    config = Config(
        keep_source=args.keep,
        output_dir=Path(args.output) if args.output else None,
        verbose=args.verbose,
        optimize_level=args.optimize,
        language_level=args.lang_level
    )
    
    logger = get_logger("py2so", config.verbose)
    
    # 验证所有文件存在
    valid_files = []
    for file_path in args.files:
        path = Path(file_path)
        if not path.exists():
            logger.warning(f"文件不存在，将跳过: {file_path}")
            continue
        if path.suffix != ".py":
            logger.warning(f"不是Python文件，将跳过: {file_path}")
            continue
        valid_files.append(path)
    
    if not valid_files:
        logger.error("没有有效的Python文件可编译")
        sys.exit(1)
    
    # 执行编译
    compiler = Compiler(config)
    results = compiler.compile_files(valid_files)
    
    # 输出汇总结果
    success_count = sum(1 for res in results.values() if res)
    logger.info(f"\n编译完成: {success_count}/{len(results)} 个文件成功")
    
    # 非零退出码表示有失败
    if success_count < len(results):
        sys.exit(1)

if __name__ == "__main__":
    main()
